package com.chenjim.glrecorder;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.PixelCopy;
import android.view.SurfaceHolder;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

public class CameraGlView extends GLSurfaceView {

    private final CameraRenderer cameraRenderer;

    public CameraGlView(Context context) {
        this(context, null);
    }

    public CameraGlView(Context context, AttributeSet attrs) {
        super(context, attrs);
        /*
         * 配置GLSurfaceView
         */
        //设置EGL版本
        setEGLContextClientVersion(2);
        cameraRenderer = new CameraRenderer(this);
        setRenderer(cameraRenderer);
        //设置按需渲染 当我们调用 requestRender 请求GLThread 回调一次 onDrawFrame
        // 连续渲染 就是自动的回调onDrawFrame
        setRenderMode(RENDERMODE_WHEN_DIRTY);
        this.paint = createPaint();
        this.mainHandler = new Handler(Looper.getMainLooper());
        getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                startAnalyzing();
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

            }
        });
    }

    private Paint paint;
    private Handler mainHandler;
    private boolean isAnalyzing = false;


    private Paint createPaint() {
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(3.0f);
        return paint;
    }

    public void startAnalyzing() {
        isAnalyzing = true;
        captureNextFrame();
    }

    private void captureNextFrame() {
        if (!isAnalyzing) return;

        // 创建与SurfaceView相同大小的Bitmap
        final Bitmap bitmap = Bitmap.createBitmap(
                getWidth(),
                getHeight(),
                Bitmap.Config.ARGB_8888
        );

        // 使用PixelCopy获取帧数据
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            PixelCopy.request(
                    this,
                    bitmap,
                    copyResult -> {
                        if (copyResult == PixelCopy.SUCCESS) {
                            processFrame(bitmap);
                        }
                        // 安排下一帧捕获
                        mainHandler.postDelayed(() -> captureNextFrame(), 33); // ~30fps
                    },
                    mainHandler
            );
        }
    }

    private void processFrame(Bitmap bitmap) {
        // 在这里进行图像分析
        List<Rect> detections = new ArrayList<>();
        drawDetections(detections);
    }

    private void drawDetections(List<Rect> detections) {
        Canvas canvas = getHolder().lockCanvas();
        Log.d("drawDetections", "----" + (canvas == null));
        if (canvas != null) {
            try {
                // 清除上一帧
                canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                // 绘制检测框
                for (Rect detection : detections) {
                    canvas.drawRect(detection, paint);
                }
            } finally {
                getHolder().unlockCanvasAndPost(canvas);
            }
        }
    }

    public void stopAnalyzing() {
        isAnalyzing = false;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        super.surfaceDestroyed(holder);
        cameraRenderer.onSurfaceDestroyed();
        mainHandler.removeCallbacksAndMessages(null);
    }


    public void startRecord() {
        float speed = 1.f;
        cameraRenderer.startRecord(speed);
    }

    public void stopRecord() {
        cameraRenderer.stopRecord();
    }

    public void saveFile() {
        cameraRenderer.saveFile();
    }

}
